<script setup>
import { onMounted } from 'vue';
import { get, post, del,put } from '@/http/http';
import { ref } from 'vue';
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const pageNum = ref(1);
const pageSize = ref(3);
const size = ref(4);
const total = ref(5);
const tableData = ref([
    {
        id: 1,
        title: 'title',
        image: 'image',
        intro: 'intro',
        content: 'content',
        consultant_id: 'consultant_id',
        publishTime: 'publish_time',
        consultant: {
            username: ''
        }
    },
]);



const addshow= ref();
const updateshow=ref();


onMounted(() => {
    flush();
})

function flush() {
    let a = JSON.parse(sessionStorage.getItem("consultant"));
    console.log("-------------------------------------")
    console.log(a)
    let id
    
    if(a==null){
        id = -1
        console.log(id)
    }else{
        id = a.id
        console.log(id)
    }


    get("/dmy/featuredArticle/findAll",
        {
            id:id,
            pageNum: pageNum.value,
            pageSize: pageSize.value
        })
        .then((res) => {
            tableData.value = res.data.list;
            pageNum.value = res.data.pageNum;
            pageSize.value = res.data.pageSize;
            size.value = res.data.size;
            total.value = res.data.total;
        })
        .catch((err) => {
            console.log(err);
        })
}

//分页
const handleSizeChange = (sizeNew) => {
    pageSize.value = sizeNew;
    flush();
}
const handleCurrentChange = (pageNew) => {
    pageNum.value = pageNew;
    flush();
}

//查询
const input = ref('');
const searchBtn = () => {
    let a = JSON.parse(sessionStorage.getItem("consultant"));
    console.log("-------------------------------------")
    console.log(a)
    let id
    
    if(a==null){
        id = -1
        console.log(id)
    }else{
        id = a.id
        console.log(id)
    }

    get("/dmy/featuredArticle/findByTitle", {
        id:id,
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        title: input.value
    }).then((res) => {
        tableData.value = res.data.list;
        console.log("----------------------------------------------+++++++")
        console.log(tableData.value)
        console.log(res.data.list)
        // pageNum.value = res.data.pageNum;
        // pageSize.value = res.data.pageSize;
        // size.value = res.data.size;
        // total.value = res.data.total;
    }).catch((err) => {
        console.log(err);
    })
}

function tianjia(){
    id.value=''
        title.value = ''
        image.value = ''
        intro.value = ''
        content.value = ''
        consultantId.value = ''
        publishTime.value = ''
        imageUrl.value = ''
    centerDialogVisible.value = true ; 
    addshow.value= true ;
    updateshow.value=false;
}

//对话框
const centerDialogVisible = ref(false)
const id = ref()
const title = ref()
const image = ref()
const intro = ref()
const content = ref()
const consultantId = ref()
const publishTime = ref()

const add = () => {
    if (title.value == null || consultantId.value == null) {
        alert("title和consultantId不可为空")
        return;
    }
    centerDialogVisible.value = false;
    post('/dmy/featuredArticle/add',
        {
            "title": title.value,
            "image": image.value,
            "intro": intro.value,
            "content": content.value,
            "consultantId": consultantId.value,
            "publishTime": publishTime.value
        }
    ).then((resp) => {
        console.log(resp)
        centerDialogVisible.value = false
        id.value=''
        title.value = ''
        image.value = ''
        intro.value = ''
        content.value = ''
        consultantId.value = ''
        publishTime.value = ''
        imageUrl.value = ''
        flush()

    }).catch((err) => {
        console.log(err)
    })

}

//选择器,获取咨询师id 和姓名传送
const options = [
    {
        value: '1',
        label: '小明',
    },
    {
        value: '2',
        label: '小李',
    },

]
//图片上传

const imageUrl = ref('')
// 自定义上传逻辑
const customUpload = async (options) => {
    const { file } = options;
    const formData = new FormData();
    formData.append('file', file);
    formData.append('subPath', 'images/Aritcle');
    console.log(options)
    try {
        const response = await fetch('/api/img', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (result.code === 200) {
            console.log(result)
            image.value = result.data;
            imageUrl.value = `http://localhost:8080/img?imgUrl=${result.data}`;
            ElMessage.success('图片上传成功');
        } else {
            ElMessage.error(result.message || '图片上传失败');
        }
    } catch (error) {
        ElMessage.error('上传过程中出现错误');
        console.error('Upload error:', error);
    }
};
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}



//编辑scope
function handleEdit(e) {
    addshow.value=false;
    updateshow.value=true;

    console.log(e);

    id.value = e.id
    title.value = e.title
    image.value = e.image
    intro.value = e.intro
    content.value = e.content
    consultantId.value = e.consultantId
    publishTime.value = e.publishTime
    imageUrl.value = `http://localhost:8080/img?imgUrl=${e.image}`
    centerDialogVisible.value = true

    


}
function update(){
    put('/dmy/featuredArticle/update',
        {
            "id":id.value,
            "title": title.value,
            "image": image.value,
            "intro": intro.value,
            "content": content.value,
            "consultantId": consultantId.value,
            "publishTime": publishTime.value
        }
    ).then((resp) => {
        console.log(resp)
        centerDialogVisible.value = false
        title.value = ''
        image.value = ''
        intro.value = ''
        content.value = ''
        consultantId.value = ''
        publishTime.value = ''
        imageUrl.value = ''
        flush()

    }).catch((err) => {
        console.log(err)
    })
}


// 删除
function handleDelete(b) {

    console.log(b.id);
    del('/dmy/featuredArticle/delete',
        {
            params: {
                id: b.id
            }
        }).then((resp) => {
            console.log(resp)
        }).catch((err) => {
            console.log(err)
        })

    flush()

}
//批量删
const multipleSelection = ref([])
let arr=[]

const handleSelectionChange = (val) => {
  multipleSelection.value = val
    console.log(val)
   const a = new Array();
   for(let i=0;i<val.length;i++){
        a.push(multipleSelection.value[i].id)
   }
   arr=a
   console.log(arr)
   console.log(a)
}

function deleteBatch(){
    console.log(arr)
    post("/dmy/featuredArticle/deleteByPrimaryKeys",
        arr
    ).then((resp)=>{
        console.log(resp)
    }).catch((error)=>{
        console.log(error)
    })
    flush()
}
 

</script>

<template>
    <!-- 对话框 -->
    <el-dialog v-model="centerDialogVisible" title="添加" width="500" align-center>
        <div class="dialog-input-class">id:<el-input v-model="id" disabled class="d-a-class" /></div>
        <div class="dialog-input-class">title:<el-input v-model="title" class="d-a-class" /></div>
        <!-- 图片 -->
        <div class="dialog-input-class">image:
            <el-input v-model="image" class="d-a-class" />
            <el-upload name="file" class="avatar-uploader" action="#"
                :on-change="(file) => customUpload({ file: file.raw })" :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </div>
        <div class="dialog-input-class">intro:<el-input v-model="intro" class="d-a-class" /></div>
        <div class="dialog-input-class">content:<el-input v-model="content" type="textarea" class="d-a-class" /></div>
        <div class="dialog-input-class">consultantId:
            <el-select class="d-a-class" v-model="consultantId" placeholder="Select" style="width: 240px">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </div>
        <div class="dialog-input-class">publishTime:
            <el-date-picker class="d-a-class" v-model="publishTime" type="datetime" placeholder="Select date and time"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取消</el-button>
                <el-button type="primary" v-if="addshow" @click="add">
                    确定
                </el-button>
                <el-button type="primary" v-if="updateshow" @click="update">
                    更新
                </el-button>
            </div>
        </template>
    </el-dialog>

    <div>
        <div class="search-class">
            <label class="label-class">标题:</label>
            <el-input v-model="input" class="input-class" placeholder="Please input" />
            <el-button type="primary" class="button-class" @click="searchBtn">查询</el-button>
        </div>
        <div class="buttons-class">
            <el-button type="primary" class="button-class" @click="tianjia">添加</el-button>
            <el-button type="danger" class="button-class" @click="deleteBatch">删除</el-button>
        </div>
        <div>
            <el-table :data="tableData" style="width: 100%" ref="multipleTableRef" row-key="id"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="55" />
                <el-table-column prop="id" label="id" width="55" />
                <el-table-column prop="title" label="title" width="180" />
                <el-table-column label="image" width="180">
                    <template #default="scope">

                        <img :src="`http://localhost:8080/img?imgUrl=${scope.row.image}`" alt="Image"
                            style="width: 100px; height: 60px; object-fit: cover;" />

                        <!-- <img :src=scope.row.image alt="在加载" > -->
                    </template>
                </el-table-column>
                <el-table-column prop="intro" label="intro" width="180" />
                <el-table-column prop="content" label="content" width="180" />
                <el-table-column prop="consultant.username" label="consultant_id->name" width="180" />
                <el-table-column prop="publishTime" label="publish_time" width="180" />
                <el-table-column label="操作列表" width="180">
                    <template #default="scope">
                        <div>
                            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div>
            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[2, 5, 10]"
                :size="size" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </div>
</template>

<style lang="less" scoped>
div {
    border: 1px solid rgba(0, 0, 0, 0);
}

.search-class {
    .label-class {
        margin-right: 20px;
        color: grey;
    }

    .input-class {
        width: 240px;
        border-radius: 5px;
    }

    .button-class {
        margin-left: 20px;
    }
}

.buttons-class {
    margin: 20px 0;
}

.dialog-input-class {
    margin: 0 0 20px 20px;

    .d-a-class {
        width: 240px;
        margin-left: 20px;
    }

}

/* 图片上传 */
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
